<template>
  <div class="user-profile">
    <!-- 查看模式 -->
    <el-card v-if="isEditing===0" class="box-card">
      <h2 slot="header">用户信息</h2>
      <div class="user-info">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用户名">{{ currentUser.adminId }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ currentUser.name }}</el-descriptions-item>
          <el-descriptions-item label="权限">{{ currentUser.permission===1?'普通员':currentUser.permission===2?'超级管理员':'原始管理员' }}</el-descriptions-item>
          <el-descriptions-item label="信息"> 
            <template #default>
              <span style="white-space: pre-wrap;">{{ currentUser.adminText }}</span>
            </template></el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentUser.create }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <el-button-group class="actions">
        <el-button @click="changePassword">修改密码</el-button>
        <el-button @click="changeInfo">修改信息</el-button>
        <el-button @click="logot">退出登录</el-button>
      </el-button-group>
    </el-card>

    <!-- 更改密码 -->
    <el-form v-else-if="isEditing===1" :model="form" :rules="passwordrules" @submit.prevent="passwordSubmit" label-width="100px" class="edit-form">
      <h2 slot="header">修改密码</h2>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" type="password" :minlength="6" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item class="form-actions">
        <el-button-group>
          <el-button type="primary" native-type="submit">保存修改</el-button>
          <el-button type="info" @click="cancelEdit">取消</el-button>
        </el-button-group>
      </el-form-item>
    </el-form>


    <!-- 编辑用户信息 -->
    <el-form v-else-if="isEditing===2" @submit.prevent="infoSubmit" :rules="inforules"  label-width="100px" class="edit-form">
      <h2 slot="header">修改用户信息</h2>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" required></el-input>
      </el-form-item>
      <el-form-item label="信息">
        <el-input type="textarea" :autosize="{ minRows: 6 }" v-model="form.adminText" required></el-input>
      </el-form-item>
      <el-form-item class="form-actions">
        <el-button-group>
          <el-button type="primary" native-type="submit">保存修改</el-button>
          <el-button type="info" @click="cancelEdit">取消</el-button>
        </el-button-group>
      </el-form-item>
    </el-form>
    
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getInfo, updateUser, logout } from '@/api/Login'
import { useRouter } from 'vue-router'
import { ElCard, ElDescriptions, ElDescriptionsItem, ElButtonGroup, ElButton, ElForm, ElFormItem, ElInput, ElMessage } from 'element-plus'

// 获取路由
const router = useRouter()

// 用户信息实体
const currentUser = ref({
  adminId: 'user123',
  name: '张三',
  permission: 0,
  adminText: '测试信息\n测试信息\n测试信息\n',
  create: '2021-11-11 11:11:11'
})

onMounted(() => {
  getInfo().then(res => {
    if(res.data.code === 200){
      currentUser.value = res.data.data;
    }
    else{
      showMessage('获取用户信息失败', 'error')
    }
  })
})

// 编辑状态
const isEditing = ref(0)

// 表单数据
const form = reactive({})

// 修改密码
const changePassword = () => {
  form.newPassword = ''
  form.confirmPassword = ''
  isEditing.value=1;
}

// 开始编辑
const changeInfo = () => {
  form.name = currentUser.value.name
  form.adminText=currentUser.value.adminText
  isEditing.value=2;
}

// 密码验证规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== form.newPassword) {
    callback(new Error('两次密码输入不一致'))
  } else {
    callback()
  }
} 
const passwordrules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '新密码长度至少为6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}


// 提交表单
const passwordSubmit = async () => {
  // 密码修改逻辑验证

  const res = await updateUser({
    adminId: currentUser.value.adminId,
    passwd: form.newPassword
  })
  if (res.data.code !== 200) {
    showMessage('密码修改失败')
    return
  }
  showMessage('密码修改成功')
  isEditing.value = 0;
}

const inforules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 0, message: '姓名不能为空', trigger: 'blur' }
  ]
}
const infoSubmit = async () => {
  // 用户信息修改逻辑验证
  if (!form.name) {
    showMessage('姓名不能为空', 'error')
    return
  }

  const res = await updateUser({
    adminId: currentUser.value.adminId,
    name: form.name,
    adminText: form.adminText
  })
  if (res.data.code !== 200) {
    showMessage('信息修改失败')
    return
  }else{
    currentUser.value.name = res.data.data.name
    currentUser.value.adminText = res.data.data.adminText
  }
  showMessage('信息修改成功')
  isEditing.value = 0;
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = 0
}

// 退出登录
const logot = () => {
  logout().then(() => {
    router.push('/login')
  })
}

// 消息提示（同原组件逻辑）
const showMessage = (text, type = 'success') => {
  ElMessage({
    message: text,
    type: type,
    duration: 3 * 1000
  })
}
</script>

<style scoped>
/* 沿用原有样式并扩展 */
.user-profile {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
}

.actions {
  margin-top: 20px;
  text-align: right;
}

.edit-form {
  padding: 20px;
}
</style>
